package neuralmusic.brain.module;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


public  abstract class BasicDelayed implements Delayed {
	
	protected double when;       // time we want to fire
	
	private boolean firing = false;
	protected Scheduler sched;
	
	public BasicDelayed(){
	}
	
	public BasicDelayed(Scheduler queue){
		this.sched=queue;
	}
	
	
	@Override
	final public int compareTo(Delayed o) {
		double i = when;
		double j = ((BasicDelayed)o).when;
		if (i < j) {
			return -1;
		}
		if (i > j) {
			return 1;
		}
		return 0;
	}

	
	final public boolean isFiring() {
		return firing;
	}


	public abstract void fireImpl(Scheduler sched) throws BrainException;
	
	final public void fire() throws BrainException {
		fireImpl(this.sched);
		firing=false;
	}
	
	final public double getWhen() {
		return when;
	}

	final public void fireAt(double when) {
		assert(when > this.when);	
		assert(!firing);
		this.when=when;
		sched.add(this);
		firing = true;
	} 
	
	final public void fireAtDelta(double dt) {
		fireAt(sched.getCurrentTimeInSecs()+dt);
		//fireAt(when+dt);
	}
	
	@Override
	final public long getDelay(TimeUnit unit) {
		return sched.getDelay(unit,when);
	}
	
	
	public void setScheduler(Scheduler fireQueue) {
		this.sched=fireQueue;
		
	}
}
